package com.waidi.clothespad;
import android.Manifest;
import android.app.AlarmManager;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.widget.Toast;

import com.nostra13.universalimageloader.utils.L;
import com.waidi.clothespad.common.BootCompletedReceiver;
import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.FaultInfo;
import com.waidi.clothespad.common.MessageToUi;
import com.waidi.clothespad.common.MyToast;
import com.waidi.clothespad.common.RfidData;
import com.waidi.clothespad.common.VerData;
import com.waidi.clothespad.common.WorkerInfo;
import com.waidi.clothespad.fragment.FragGongyishipin;
import com.waidi.clothespad.fragment.FragHouDaoqc;
import com.waidi.clothespad.fragment.FragHouProduct;

import com.waidi.clothespad.fragment.FragLineOut;
import com.waidi.clothespad.fragment.FragShengchantongji;
import com.waidi.clothespad.fragment.FragShenglineqc;
import com.waidi.clothespad.fragment.FragShenglineqc2;
import com.waidi.clothespad.fragment.FragShishishuju;
import com.waidi.clothespad.mqttclient.MyMqttClient;
import com.waidi.clothespad.thread.SerialTask;
import com.waidi.clothespad.thread.handlethread;
import com.waidi.clothespad.common.CommonProgressDialog;
import com.waidi.clothespad.common.DownloadTask;

import com.waidi.clothespad.ui.QrCodeBoundDialog;
import com.waidi.clothespad.ui.SalaryDialog;
import com.waidi.clothespad.ui.ScrollingActivity_worker_product;
import com.waidi.clothespad.ui.SettingDialog;
import com.waidi.clothespad.ui.WorkerProductActivity;
import com.zhy.android.percent.support.PercentLinearLayout;
import com.zhy.android.percent.support.PercentRelativeLayout;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClothesMainActivity extends Activity {
/*    @BindView(R.id.iv_more)
    RelativeLayout ivMore;*/
    @BindView(R.id.iv_eth0)
    ImageView ivEth0;

    @BindView(R.id.iv_wifi)
    ImageView ivWifi;

    @BindView(R.id.iv_mqtt)
    ImageView ivmqtt;

    @BindView(R.id.wifi_signal_des)
    TextView wifi_signal_des;
    @BindView(R.id.tv_dev_id)
    TextView tV_dev_id;


    @BindView(R.id.rl_menu)
    PercentRelativeLayout rlMenu;
    @BindView(R.id.rl_shishishuju)
    PercentRelativeLayout rlShishishuju;
    @BindView(R.id.rl_gongyishipin)
    PercentRelativeLayout rlGongyishipin;
    @BindView(R.id.rl_lineQc)
    PercentRelativeLayout rlLineQc;

    @BindView(R.id.rl_productQuery)
    PercentRelativeLayout rlProductQuery;

    @BindView(R.id.rl_lineOut)
    PercentRelativeLayout rlLineOut;


    @BindView(R.id.iv_menu)
    ImageView ivMenu;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.iv_arrow_left)
    ImageView ivArrowLeft;
    @BindView(R.id.iv_touxiang)
    ImageView ivTouxiang;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_ver)
    TextView tvVer;


    @BindView(R.id.tv_login_time)
    TextView tvLoginTime;

    @BindView(R.id.ll_shishishuju_expand)
    LinearLayout llShishishujuExpand;
    @BindView(R.id.ll_gongyishipin_expand)
    LinearLayout llGongyishipinExpand;

    @BindView(R.id.ll_lineQc_expand)
    LinearLayout llLineQcExpand;
    @BindView(R.id.ll_productQuery_expand)
    LinearLayout llProductQueryExpand;

    @BindView(R.id.ll_lineOut_expand)
    LinearLayout llLineOutExpand;


    @BindView(R.id.rl_frag_container)
    PercentRelativeLayout rlFragContainer;
    @BindView(R.id.ll_menu_layer_expand)
    PercentLinearLayout llMenuLayerExpand;

    @BindView(R.id.mainactivity_left_menu_list)
    PercentLinearLayout ll_mainactivity_left_menu_list;


    Animation anim_menu_trans_x_in;
    Animation anim_menu_trans_x_out;
    int menu_index=0;
    FragmentTransaction fragmentTransaction;
    FragmentManager fragManager ;
    SettingDialog settingDialog;
    private CommonProgressDialog pBar;

    private int click0 = 0;
    private int click1 = 0;
    private int click2 = 0;
    //add ll
    public String TAG = "ClothesMainActivity";
    private BootCompletedReceiver receiver =null;
    private boolean onDestroy = false;
    public  static SerialTask serialtask =null ;
    public handlethread t1=null;
    public MyMqttClient mqttClient = null;
    public AlertDialog storeErrDialogBuilder = null;

    public MyHandler handler;
    public TimerHandler timerhandler;
    public boolean sdCardPerssion = false;

    public Context context;



    public int current_position = 0;
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //需要自己定义标志


    String[] permissions = new String[]
    {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //强制横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //屏蔽HOME键
       // this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//关键代码

        setContentView(R.layout.activity_clothes_main_precent);
        ButterKnife.bind(this);
        context = this.getApplicationContext();

/*      6.0和6.0以后在权限管理方面更加全面，在读写外置存储的时候不仅要在manifest中静态授权，还需要在代码中动态授权。*/

        if (Build.VERSION.SDK_INT>22){


      /*      if (ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
                Log.i(TAG,"获取存储权限0");
            }else {
                //说明已经获取到摄像头权限了 想干嘛干嘛
                Log.i(TAG,"已经获取到存储权限了0");
            }

            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
                Log.i(TAG,"获取存储权限1");
            }else {
                //说明已经获取到摄像头权限了 想干嘛干嘛
                Log.i(TAG,"已经获取到存储权限了1");
            }


            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                //先判断有没有权限 ，没有就在这里进行权限的申请
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.CAMERA},3);
                Log.i(TAG,"获取到摄像头权限");
            }else {
                //说明已经获取到摄像头权限了 想干嘛干嘛
                Log.i(TAG,"已经获取到摄像头权限了");
            }
        }else {
//这个说明系统版本在6.0之下，不需要动态获取权限。
            Log.i(TAG,"系统版本在6.0之下，不需要动态获取权限");*/



            mPermissionList.clear();
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(ClothesMainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (mPermissionList.isEmpty())
            {
                //未授予的权限为空，表示都授予了
                Toast.makeText(ClothesMainActivity.this,"已经授权",Toast.LENGTH_LONG).show();
            } else {//请求权限方法
                String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
                ActivityCompat.requestPermissions(ClothesMainActivity.this, permissions, 2);
            }
        }
        sdCardPerssion = false;
        handler = new MyHandler();
        Config.MainActivityHandler = handler;
        timerhandler = new TimerHandler();
//        setContentView(R.layout.layer_title);
        //菜单层展开，菜单层隐藏
        //菜单切换，Fragment切换


        Config config = new Config(context);
        config.init();
        tvVer.setText("V"+Config.ver);

        serialtask = new SerialTask(handler,this);
        int fd = serialtask.fd;
        if(fd>0)
        {
            Log.i("serial-task",Integer.toString(fd));
            serialtask.start();
        }
        else
        {
            AlertDialog.Builder builder  = new AlertDialog.Builder(this);
            builder.setTitle("提示" ) ;
            builder.setMessage("读卡设备打开失败!" ) ;
            builder.setPositiveButton("是" ,  null );
            builder.show();
        }

        Log.i(TAG,"================");
        initParam();
        initElem();
        init_workerinfo();

/*        SalaryDialog salaryDialog = new SalaryDialog(ClothesMainActivity.this);
        salaryDialog.show();*/

 /*       Intent intent = new Intent(ClothesMainActivity.this, WorkerProductActivity.class);
        startActivity(intent);*/

        timer.schedule(task,60000,20000); //定时获取服务端的版本
        timer.schedule(task2,5000,1000);

        new MessageToUi().send(10002,"info"," ",handler);

        if(isRoot())
        {
           // MyToast.showToast(context,"root");
        }

    }

    void init_workerinfo()
    {


        if(Config.rfidWorkerInfo.workername.length()!=0)
        {
            tvName.setText(Config.rfidWorkerInfo.workername);
            tvLoginTime.setText(Config.rfidWorkerInfo.logtime);
        }
    }

    /**
     * 判断是否拥有Root权限。
     * @return 有root权限返回true，否则返回false。
     */
    public boolean isRoot() {
        boolean bool = false;
        try {

            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        // TODO:  some code
       // unregisterReceiver(receiver);//必须注销掉注册过广播
        if(settingDialog!=null)
            settingDialog.dismiss();
    }


    @Override
    public void onStart()
    {
        super.onStart();
        checkStorePerssion();

    }

    @Override
    public void onResume()
    {
        super.onResume();

    }

    @Override

    public void onStop()
    {
        super.onStop();
    }

    //back键默认把当前Activity给finish，home键只是把Activity给onStop.
    private int pressedBackNo = 0;
    @Override
    public void onBackPressed() {
        pressedBackNo++;
        if(pressedBackNo <=1 )
        {
            MyToast.showToast(context, "再点击一次就退出...");
            return;
        }
        System.exit(0);//正常退出App
        super.onBackPressed();
    }


    private void initParam() {
        fragManager = this.getFragmentManager();
         anim_menu_trans_x_in = AnimationUtils.loadAnimation(
                ClothesMainActivity.this, R.anim.menu_trans_x_in);
         anim_menu_trans_x_out = AnimationUtils.loadAnimation(
                ClothesMainActivity.this, R.anim.menu_trans_x_out);
    }

    private void initElem()
    {
        /*
        Fragment fragment = new FragShishishuju();
        fragmentTransaction.add(R.id.rl_frag_container,fragment);
        fragmentTransaction.commit();
        */
        changeFragment(menu_index);
    }

    @OnClick(R.id.iv_setting)
    public void showSettingdialog(){
        if (null == settingDialog)
        {
            settingDialog = new SettingDialog(ClothesMainActivity.this,handler);
        }
        settingDialog.show();

    }
    @OnClick(R.id.tv_time)
    public void showSetting(){
        if(click1==5) {

            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            click1 = 0;
        }click1++;
    }

    @OnClick(R.id.iv_wifi)
    public void showSettingWifi(){
        if(click2==5) {
            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            startActivity(intent);
            click2 = 0;
        }click2++;
    }


    @OnClick(R.id.iv_touxiang)
    public void exitClothesMainActivity()
    {
    //置全屏
        if(click0==3) {
            System.exit(0);//正常退出App 调试使用
/*            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
            click0 = 0;
        }
        click0++;

    }


    @OnClick(R.id.rl_menu)
    public void showMenuLayerExpand(){
        rlMenu.setVisibility(View.GONE);
        llMenuLayerExpand.setVisibility(View.VISIBLE);
        llMenuLayerExpand.startAnimation(anim_menu_trans_x_in);
    }
    @OnClick(R.id.iv_arrow_left)
    public void closeMenuLayerExpand(){
        llMenuLayerExpand.setVisibility(View.GONE);
        rlMenu.setVisibility(View.VISIBLE);
        llMenuLayerExpand.startAnimation(anim_menu_trans_x_out);
    }
    @OnClick(R.id.rl_shishishuju)
    public void menu_shishishuju(){
        menu_index=0;
        //切换背景颜色
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);

        if(click1==99995) {
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            click1 = 0;
        }
       // click1 ++;

    }

    @OnClick(R.id.rl_gongyishipin)
    public void menu_gongyishipin(){
        menu_index=1;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }

    @OnClick(R.id.rl_lineQc)
    public void menu_shengchantongji(){
        menu_index=2;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);

/*        String url = "http://" + Config.devConfig.web_addr + "/js/a/its/terminal/faultInfo?";
        sendRequestDefect(url);*/
    }
    @OnClick(R.id.rl_productQuery)
    public void menu_kaoqintongji(){
        menu_index=3;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }
    @OnClick(R.id.rl_lineOut)
    public void menu_hujiaotongji(){
        menu_index=4;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }

    @OnClick(R.id.ll_shishishuju_expand)
    public void menu_expan_shishishuju(){
        menu_index=0;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }
    @OnClick(R.id.ll_gongyishipin_expand)
    public void menu_expan_gongyishipin(){
        menu_index=1;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }
    @OnClick(R.id.ll_lineQc_expand)
    public void menu_expan_shengchantongji(){
        menu_index=2;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }


    @OnClick(R.id.ll_productQuery_expand)
    public void menu_expan_kaoqintongji(){
        menu_index=3;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }


    @OnClick(R.id.ll_lineOut_expand)
    public void menu_expan_hujiaotongji(){
        menu_index=4;
        changeMenuLayerBackgroud(menu_index);
        changeExpandMenuLayerBackgroud(menu_index);
        changeFragment(menu_index);
    }

    private void changeMenuLayerBackgroud(int menu_index)
    {
        setDefaultBackgroudColor();
        switch (menu_index){
            case 0:
               /* rlShishishuju.setBackgroundColor(Color.parseColor("#17897F"));*/
                rlShishishuju.setBackgroundColor(Color.parseColor("#17897F"));

                break;
            case 1:
                rlGongyishipin.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 2:
                rlLineQc.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 3:
                rlProductQuery.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 4:
                rlLineOut.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            default:
                break;
        }
    }
    private void changeExpandMenuLayerBackgroud(int menu_index)
    {
        setExpandDefaultBackgroudColor();
        switch (menu_index){
            case 0:
                /*llShishishujuExpand.setBackgroundColor(Color.parseColor("#17897F"));*/
                 llShishishujuExpand.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 1:
                llGongyishipinExpand.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 2:
                llLineQcExpand.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 3:
                llProductQueryExpand.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            case 4:
                llLineOutExpand.setBackgroundColor(Color.parseColor("#17897F"));
                break;
            default:
                break;
        }
    }
    private void setDefaultBackgroudColor() {
        rlShishishuju.setBackgroundColor(Color.parseColor("#1EB4A8"));
       /* rlShishishuju.setBackgroundColor(Color.parseColor("#1EB4A8"));*/
        rlGongyishipin.setBackgroundColor(Color.parseColor("#1EB4A8"));
        rlLineQc.setBackgroundColor(Color.parseColor("#1EB4A8"));
        rlProductQuery.setBackgroundColor(Color.parseColor("#1EB4A8"));
        rlLineOut.setBackgroundColor(Color.parseColor("#1EB4A8"));
    }
    private void setExpandDefaultBackgroudColor() {
        llShishishujuExpand.setBackgroundColor(Color.parseColor("#1EB4A8"));
        llGongyishipinExpand.setBackgroundColor(Color.parseColor("#1EB4A8"));
        llLineQcExpand.setBackgroundColor(Color.parseColor("#1EB4A8"));
        llProductQueryExpand.setBackgroundColor(Color.parseColor("#1EB4A8"));
        llLineOutExpand.setBackgroundColor(Color.parseColor("#1EB4A8"));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return true;
    }



    private HashMap<String,Fragment> fragMap = new HashMap<String,Fragment>();
    private Context mActivity;

    private static final String frag0 = "shishishuju";
    private static final String frag1 = "gongyishipin";
    private static final String frag2 = "lineqc";
    private static final String frag3 = "productQuery";
    private static final String frag4 = "FragLineOut";

    private FragShishishuju fragment0  =null;
    private FragGongyishipin fragment1  =null;
  //  private FragShenglineqc fragment2 =null;
    private FragShenglineqc2 fragment2 =null;
    private FragShengchantongji fragment3 =null;
    private FragLineOut fragment4 =null;
    private Fragment tmp = null;
    private boolean fragment2_show = false;

    private void changeFragment(int menu_index) {
    try
        {

        Config.fragment_index = menu_index;
        fragmentTransaction = fragManager.beginTransaction();
        if(menu_index==2)
            Config.hangerinfosyncflag =1;
        else
            Config.hangerinfosyncflag =0;

        switch (menu_index)
        {
            case 0:
                if (null == fragment0){
                    fragment0 = new FragShishishuju();
                    Config.fragShishishuju= fragment0 ;
                    Config.fragShishishuju.Activityhandler = handler;
                    Log.i(TAG,frag0);
                    if(t1==null)
                    {
                        t1 = new handlethread(fragment0.handler,context);
                        t1.handler0 = fragment0.handler;
                        t1.handler1 = handler;
                        t1.calltype = fragment0.calltype;

                        mqttClient = new MyMqttClient();
                        mqttClient.start();

                        //t1.start();
                        //calThread = new CalThread();
                        // 启动新线程
                       //fragment0.calThread = calThread
                        //calThread.start();
                    }
                    fragmentTransaction.add(R.id.rl_frag_container,fragment0,Integer.toString(menu_index));
                    fragmentTransaction.commit();
                }
                else
                {
                    fragmentTransaction.hide(tmp).show(fragment0).commit(); // 隐藏当前的fragment，显示下一个
                }
                tmp = fragment0;
                break;
            case 1:
                if (null == fragment1)
                {
                    fragment1 = new FragGongyishipin();
                    Config.fragmentvideo = fragment1;
                    Log.i(TAG,frag1);
                    fragmentTransaction.hide(tmp).add(R.id.rl_frag_container,fragment1,Integer.toString(menu_index));
                    fragmentTransaction.commit();
                }
                else
                {
                    fragmentTransaction.hide(tmp).show(fragment1).commit(); // 隐藏当前的fragment，显示下一个
                }
                tmp = fragment1;
                break;
            case 2: //dg qc
                if (fragment2==null)
                {
                    fragment2 = new FragShenglineqc2();
                    Config.fragShenglineqc2 = fragment2;
                    t1.handler2 = fragment2.handler;
                    Log.i(TAG,frag2);
                    fragmentTransaction.hide(tmp).add(R.id.rl_frag_container,fragment2,Integer.toString(menu_index));
                    fragmentTransaction.commit();
                }
                else
                {
                    fragmentTransaction.hide(tmp).show(fragment2).commit();
                }
                tmp = fragment2;
                break;
            case 3://
                if (null == fragment3)
                {
                    fragment3 = new FragShengchantongji();
                    Log.i(TAG,frag3);
                    //Config.fragmenthoudao = fragment3 ;
                    fragmentTransaction.hide(tmp).add(R.id.rl_frag_container,fragment3,Integer.toString(menu_index));
                    fragmentTransaction.commit();
                }
                else
                {
                    fragmentTransaction.hide(tmp).show(fragment3).commit();
                }
                tmp = fragment3;
                break;
            case 4:
                if (null == fragment4){
                    fragment4 = new FragLineOut();
                    Config.fragLineOut = fragment4 ;
                    Log.i(TAG,frag4);
                    fragmentTransaction.hide(tmp).add(R.id.rl_frag_container,fragment4,Integer.toString(menu_index));
                    fragmentTransaction.commit();
                }
                else
                {
                    fragmentTransaction.hide(tmp).show(fragment4).commit();
                }
                tmp = fragment4;
                break;
            default:
                break;
        }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public void onShowCustomToast(View view) {


        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.mytoast,
                null);

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("rfid success");

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    public void sendRequestDefect(String url)
    {
        httpgetdefect thread = new httpgetdefect(fragment2.handler,context,url);
        thread.start();
    }

    public class httpgetdefect extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;

        public httpgetdefect(Handler handlerin, Context contextin, String url)
        {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run()
        {
            Message msg1;
            String result = "";
            HttpClient httpCient = new DefaultHttpClient();
            try
            {
                HttpGet httpGet = new HttpGet(Url);
                int code = -1;

                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get call reponse code: "+Integer.toString(code));
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                    try {
                        JSONObject jsonObj = new JSONObject(result);
                        if (jsonObj == null)
                            return;

                        String res = jsonObj.getString("result");
                        if(res.compareTo("true")==0)
                        {
                            Log.i(TAG,"获取缺陷成功！");
                            JSONArray qcArray = jsonObj.getJSONArray("data");
                            if(qcArray==null)
                                return;
                            if(qcArray.length()!=0)
                                Config.faultInfoArrayList.clear();
                            for (int i=0;i<qcArray.length();i++)
                            {
                                JSONObject s= (JSONObject)qcArray.get(i);
                                FaultInfo tmp = new FaultInfo();
                                tmp.fault_name =s.getString("fault_name");
                                tmp.fault_code = s.getString("fault_code");
                                tmp.clickedList = 0;
                                Config.faultInfoArrayList.add(tmp);
                            }
                            File gylxt = new File(Config.faultinfotxt);
                            OutputStream os = new FileOutputStream(gylxt);
                            byte b[] = jsonObj.toString().getBytes("UTF-8");
                            os.write(b);
                            os.close();
                            msg1=handler0.obtainMessage();//每发送一次都要重新获取
                            msg1.arg1 = 2;
                            msg1.obj = code;
                            handler0.sendMessage(msg1);
                           // Toast.makeText(context, "获取缺陷成功", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Log.i(TAG,"获取缺陷失败0！");
                            String ss = jsonObj.getString("message");
                           // Toast.makeText(context, ss, Toast.LENGTH_SHORT).show();
                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    Log.i(TAG,"获取缺陷失败1！");
                    String ss = "获取缺陷错误:"+Integer.toString(code);
                    //Toast.makeText(context, ss, Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e)
            {
                Log.e(TAG, "HTTP request err......");
                e.printStackTrace();
                return;
            }
        }
    }


    public boolean isWifiAvailable(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();


        //NetworkInfo.State wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
       //if(wifi == NetworkInfo.State.CONNECTED||wifi==NetworkInfo.State.CONNECTING)


        if (activeNetInfo != null)
        {
           // Log.i(TAG,"WIFI:"+Integer.toString(activeNetInfo.getType()));

            if((activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI))
            {
                return true;
            }
            return false;
        }
        else
            return false;


    }
    public  boolean isWifiEnabled(Context context0) {
        Context myContext = context0;
        if (myContext == null) {
            throw new NullPointerException("Global context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED)
        {
            ConnectivityManager connManager = (ConnectivityManager) myContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = connManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            boolean result = wifiInfo.isConnected();
/*            if(result)
                Log.i(TAG,result+"true");
            else
                Log.i(TAG,result+"false");*/
            return result;
        }
        else
        {
            return false;
        }
    }

    public boolean isEth0Available(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null)
        {
             //Log.i(TAG,"ETH0:"+Integer.toString(activeNetInfo.getType()));

            if((activeNetInfo.getType() == ConnectivityManager.TYPE_ETHERNET))
            {
                return true;
            }
            return false;
        }
        else
            return false;
    }

    public boolean isWifiAvailable2() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected() && networkInfo
                .getType() == ConnectivityManager.TYPE_WIFI);
    }

//判断网络是否正常
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    public int isNetworkAvailable(Context context)
    {
        ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ethNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (ethNetInfo != null && ethNetInfo.isConnected())
        {
            Log.i(TAG, "ETHO UP");
        }
        if (wifiNetInfo != null && wifiNetInfo.isAvailable())
        {
            Log.i(TAG, "WIFI UP");
        }
        return  0;
    }



    private int exenum = 0;
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run()
        {
            exenum++;
            if(exenum==15) //5min 不再去获取软件版本了，无论成功失败
            {
                return;
            }
            Message message = new Message();
            message.arg1 = 102;
            timerhandler.sendMessage(message);
          //  Log.i(TAG,"主Activity 定时器工作。。。");
        }
    };

    int a = 0;


    TimerTask task2 = new TimerTask() {
        @Override
        public void run()
        {
            Message message0 = new Message();
            message0.arg1 = 10000;
            timerhandler.sendMessage(message0);
/*          if(a==0)
            {
                String path = Config.apkpath+"/"+"tps10v1.92.apk";
                installSilent(path);
                Log.i(TAG,"================================================");
                a = 1;
            }*/

// 判断wifi网络是否可用
/*            if(isWifiAvailable(context)==false)
            {
                Message message1 = new Message();
                message1.arg1 = 10001;
                timerhandler.sendMessage(message1);
                return;
            }else*/
           // isNetworkAvailable(context);
            {
                if(isNetworkConnected(context)==true)
                {
                    if(isWifiEnabled(context)==true)
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("wifi","ok");
                        Message message2 = new Message();
                        message2.arg1 = 10002;
                        message2.setData(bundle);
                      //  Log.i(TAG,"10002 wifi ok");
                        timerhandler.sendMessage(message2);
                    }
                    else
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("wifi","err");
                        Message message2 = new Message();
                        message2.arg1 = 10002;
                        message2.setData(bundle);
                       // Log.i(TAG,"10002+ wifi err");
                        timerhandler.sendMessage(message2);
                    }
                    if(isEth0Available(context)==true)
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("eth0","ok");
                        Message message2 = new Message();
                        message2.arg1 = 10003;
                        message2.setData(bundle);
                       // Log.i(TAG,"10003 eth ok");
                        timerhandler.sendMessage(message2);
                    }
                    else
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("eth0","err");
                        Message message2 = new Message();
                        message2.arg1 = 10003;
                        message2.setData(bundle);
                      //  Log.i(TAG,"10003 eth err");
                        timerhandler.sendMessage(message2);
                    }
                }
                else
                {
                    Message message3 = new Message();
                    message3.arg1 = 10004;
                    timerhandler.sendMessage(message3);
                }
            }

        }
    };

    void showTimeZone()
    {

        Calendar cal;
        cal = Calendar.getInstance();
       // cal.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

        String year = String.valueOf(cal.get(Calendar.YEAR));
        String month = String.valueOf(cal.get(Calendar.MONTH))+1;
        String day = String.valueOf(cal.get(Calendar.DATE));


        String hour;
        String minute;
        String second;

        int r = cal.get(Calendar.AM_PM);
        if (r == 0)
            hour = String.valueOf(cal.get(Calendar.HOUR));
        else
            hour = String.valueOf(cal.get(Calendar.HOUR)+12);
        minute = String.valueOf(cal.get(Calendar.MINUTE));
        second = String.valueOf(cal.get(Calendar.SECOND));

        String time_1 = year + "-" + month + "-" + day;
        String time_2 = hour + ":" + minute + ":" + second;
       // tvTime.setText(time_1+" "+time_2);



        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
//获取当前时间
        Date date = new Date(System.currentTimeMillis());
        tvTime.setText(simpleDateFormat.format(date));



      // setSysDate(2017,8,9) //need SET_TIME jurisdiction ,only system app can set
     // setSysTime(18,18);//need SET_TIME jurisdiction ,only system app can set

      //  SystemClock.setCurrentTimeMillis(10000000); //old api


    }


    public void setSysDate(int year,int month,int day){
        try {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, month);
            c.set(Calendar.DAY_OF_MONTH, day);
            long when = c.getTimeInMillis();
            if (when / 1000 < Integer.MAX_VALUE) {
                ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).setTime(when);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    public void setSysTime(int hour,int minute){

        try
        {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        long when = c.getTimeInMillis();
        if(when / 1000 < Integer.MAX_VALUE){
            ((AlarmManager)context.getSystemService(Context.ALARM_SERVICE)).setTime(when);
        }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }







    private static  String APKNAME = "APKNAME";
    private static boolean ISGETAPKVERSIONED = false;


    private void update(){

        //安装应用
        //File app = new File(Config.apkpath+"/"+)
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(Config.apkpath, APKNAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    //静默安装 无效 在launcher 模式下无效
    public String silentInstall(String apkAbsolutePath) {
        String[] args = { "pm", "install","-r", apkAbsolutePath };
        String result = "";
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write("/n".getBytes());
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        MyToast.showToast(context,result);
        Log.i(TAG,result);
        return result;
    }
    //无效 在launcher 模式下无效
    public boolean install(String apkPath) {
        boolean result = false;

        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try
        {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";

            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();

            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            Log.d("TAG", "install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            Log.e("TAG", e.getMessage(), e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                Log.e("TAG", e.getMessage(), e);
            }
        }
        if(result)
        Log.i(TAG,"true");
        else
            Log.i(TAG,"false");
        return result;
    }


    //静默安装 验证无效
    public int installSilent(String filePath) {
        File file = new File(filePath);
        if (filePath == null || filePath.length() == 0 || file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
            Log.i(TAG,"1");
            return 1;
        }

        String[] args = { "pm", "install", "-r", filePath };
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        int result;
        try {
            process = processBuilder.start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }

        // TODO should add memory is not enough here
        if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
            result = 0;
        } else {
            result = 2;
        }
        Log.i(TAG, "successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);
        return result;
    }




    /**
     * 升级系统
     *
     * @param content
     * @param url
     */
    private AlertDialog warningUpdateDialog = null;
    private int cancleClickNum = 0;
    private  int CLICKNUM  = 10;

    private void ShowDialog(int vision, String newversion, final String content,
                            final String url,final String apkname) {

        warningUpdateDialog =new android.app.AlertDialog.Builder(this)
                .setTitle("版本更新,请点击更新按钮")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        cancleClickNum = CLICKNUM +20;
                        dialog.dismiss();
                        pBar = new CommonProgressDialog(ClothesMainActivity.this);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle("正在下载");
                        pBar.setCustomTitle(LayoutInflater.from(
                                ClothesMainActivity.this).inflate(
                                R.layout.title_dialog, null));
                        pBar.setMessage("正在下载新程序...");
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(true);
                        final DownloadTask downloadTask = new DownloadTask(
                                context,handler,apkname,pBar);
                        Log.i(TAG,"APK down load from: "+url);
                        downloadTask.execute(url);
                        pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                downloadTask.cancel(true);
                            }
                        });

                    }
                })
                .setNegativeButton("取消(10)", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        cancleClickNum ++;
                        if( cancleClickNum > CLICKNUM ) //默认点击第一次 不退出窗口...,主要是提示大妈们要更新
                        {
                            cancleClickNum = 0;
                            dialog.dismiss();
                        }
                        if(cancleClickNum != 10)
                            MyToast.showLongToast(context,"取消升级,可能会导致某些功能无法使用..."+cancleClickNum+" ?");
                        else
                            MyToast.showLongToast(context,"取消升级,你好狠心,再见...."+cancleClickNum+" ?");


                    }
                })
                .create();
        warningUpdateDialog.setCanceledOnTouchOutside(false);
        warningUpdateDialog.getWindow().setDimAmount(Config.transparency);//设置昏暗度
        warningUpdateDialog.getWindow().setBackgroundDrawableResource(R.color.color_deep_blue);
        warningUpdateDialog.show();
    }


    //系统内部存储监测
    private void checkStorePerssion()
    {
        try
        {
            if(sdCardPerssion == false)
            {
                File file = new File(Environment.getExternalStorageDirectory().toString());
                if(file.canExecute() == true)
                {
                    sdCardPerssion = true;
                }
            }
            if(sdCardPerssion==false)
            {
 /*           String err = "系统获取内部存储路径错误，请尝试重新插拔电源启动终端";
            Log.e(TAG,err);
            MyToast.showToast(context,err);
            AlertDialog.Builder builder  = new AlertDialog.Builder(this);
            builder.setTitle("提示" ) ;
            builder.setMessage("系统获取内部存储错误，请尝试重新启动终端!" ) ;
            builder.setPositiveButton("是" ,  null );
            builder.show();*/

                if(storeErrDialogBuilder == null)
                {
                    storeErrDialogBuilder = new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("系统获取内部存储错误，请尝试重新插拔电源重新启动终端!").create();
                }
                storeErrDialogBuilder.getWindow().setDimAmount(0.1f);//设置昏暗度为0
                storeErrDialogBuilder.getWindow().setBackgroundDrawableResource(R.color.color_pink);
                storeErrDialogBuilder.show();
                storeErrDialogBuilder.setCanceledOnTouchOutside(false);
                MyToast.showToast(context,"系统获取内部存储错误，请尝试重新插拔电源重新启动终端!");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }


    static  int timeout0= 2;
    static  int scan_signal_timeout = 0;
    static  int scan_signal_flag = 0;
    class TimerHandler extends Handler
    {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg)
        {
            try
            {
                if(isDestroyed()||isFinishing())
                    return;

                //Log.i(TAG, "TimeerHandler arg:" + Integer.toString(msg.arg1));
                switch (msg.arg1)
                {

                    case 102:
                    {
                        try {
                            if(isNetworkConnected(context))
                            {
                                if(ISGETAPKVERSIONED==false) //判断是否已经获取到了最新版本号
                                {
                                    if (null == settingDialog) {
                                        settingDialog = new SettingDialog(ClothesMainActivity.this, handler);
                                        settingDialog.getApkVersion(1);

                                    } else {
                                        settingDialog.getApkVersion(1);

                                    }
                                }
                            }
                        }
                        catch ( Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                    break;

                    case 10000:

                        if(Config.qrCodeInfo.location.length() != 0)
                        {
                            tV_dev_id.setText(Config.qrCodeInfo.location);
                        }
                        else
                        {
                            tV_dev_id.setText("设备未绑定");
                        }


                        if(warningUpdateDialog!=null)
                        {
                            if(cancleClickNum < CLICKNUM)
                            {
                                if(warningUpdateDialog.isShowing()==false)
                                    warningUpdateDialog.show();
                            }
                        }

                        showTimeZone();
                        timeout0--;




                        if(Config.qrCodeInfo.location.length()!=6&&timeout0==1)
                        {
                            MyToast.showToast(context,"设备二维码信息未绑定或绑定错误？");
                            timeout0 = 5;
                        }

                        break;
                    case 10001:
                        ivWifi.setImageResource(R.mipmap.ic_wifi_unable);
                        break;
                    case 10002:

                        Bundle bundle0=msg.getData();
                        String state = bundle0.get("wifi").toString();
                        //Log.i(TAG,"wifi:"+state);

                        if(state.compareTo("err")==0)
                        {
                            ivWifi.setImageResource(R.mipmap.wifi_disconnect);
                            wifi_signal_des.setText("断开");
                            return;
                        }

                        //ivWifi.setImageResource(R.mipmap.signal_wifi_3_bar);
                        scan_signal_timeout++;
                        wifi_signal_des.setText("");
                        if(scan_signal_timeout>=5||scan_signal_flag==0) {
                            scan_signal_timeout = 0;
                            scan_signal_flag = 1;
                            WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                            WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();

                            int wifi = mWifiInfo.getRssi();//获取wifi信号强度
                            Log.e(TAG, wifi + "");
                            if (wifi > -50 && wifi < 0) {//最强
                                //Log.e(TAG, "强");
                                //wifi_signal_des.setText("强");
                                ivWifi.setImageResource(R.mipmap.signal_wifi_4_bar);
                            } else if (wifi > -65 && wifi <= -50) {//较强
                                //Log.e(TAG, "较强");
                                //wifi_signal_des.setText("较强");
                                ivWifi.setImageResource(R.mipmap.signal_wifi_3_bar);
                            } else if (wifi > -75 && wifi <= -65) {//较弱
                                //Log.e(TAG, "较弱");
                                //wifi_signal_des.setText("较弱");
                                ivWifi.setImageResource(R.mipmap.signal_wifi_2_bar);
                            } else if (wifi > -100&& wifi <= -75) {//弱
                                //Log.e(TAG, "弱");
                                // wifi_signal_des.setText("弱");
                                ivWifi.setImageResource(R.mipmap.signal_wifi_1_bar);
                            }
                            else if (wifi > -800 && wifi <= -100) {//微弱
                                //Log.e(TAG, "微弱");
                                // wifi_signal_des.setText("微弱");
                                ivWifi.setImageResource(R.mipmap.signal_wifi_0_bar);
                            }
                            else {
                                //无连接
                                //Log.e(TAG, "无wifi连接");
                                wifi_signal_des.setText("微弱");
                            }
                        }
                        break;
                    case 10003:
                        Bundle bundle00=msg.getData();
                        String state0 = bundle00.get("eth0").toString();
                        //Log.i(TAG,"eth0:"+state0);
                        if(state0.compareTo("err")==0)
                        {
                            ivEth0.setImageResource(R.mipmap.ic_eth0_down);
                            return;
                        }


                        ivEth0.setImageResource(R.mipmap.ic_eth0_up);
                        //Log.e(TAG, "ETh0连接");
                        break;

                    case 10004:
                        ivWifi.setImageResource(R.mipmap.wifi_disconnect);
                        wifi_signal_des.setText("断开");
                        //Log.e(TAG, "无wifi连接");
                        ivEth0.setImageResource(R.mipmap.ic_eth0_down);
                        //Log.e(TAG, "无eth0连接");
                        break;

                    default:
                        break;
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();

            }


        }
    }
    String barcode ="";
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        String code;
        Log.i(TAG,"##"+event.toString());
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    &&event.getKeyCode() != KeyEvent.KEYCODE_ENTER
                    &&event.getKeyCode()!=KeyEvent.KEYCODE_SHIFT_LEFT
                    &&event.getKeyCode()!=KeyEvent.KEYCODE_SHIFT_RIGHT)
                    //过滤掉换行符,以及键盘shfit键
            {
                Log.i(TAG, "dispatchKeyEvent: " + event.toString());
                char pressedKey = (char) event.getUnicodeChar();
                barcode += pressedKey;
            }
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                    && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
            {
                //MyToast.showToast(context,barcode);
                Log.i(TAG, "BARCODE:" + barcode);
                code = barcode;
                if(Config.fragShishishuju.isHidden() == false)
                {
                    //这部分处理原来的扫码上线和扫码切换
                    new MessageToUi().send(900, "qrcode", code, Config.fragShishishuju.handler);
                }
                else if(Config.fragLineOut != null)
                {
                    //处理线外扫码..
                    if(Config.fragLineOut.isHidden() == false)
                    {
                        new MessageToUi().send(900, "qrcode", code, Config.fragLineOut.handler);
                    }
                }

                barcode = "";
            }
        }
        return super.dispatchKeyEvent(event);
    }

/*    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
        super.onKeyUp(keyCode, event);
      //  setTitle("you release key:" + String.valueOf(keyCode));

        Log.i(TAG,"**"+event.toString());
        return true;
    }*/

    /**
     * 接受消息，处理消息 ，此Handler会与当前主线程一块运行
     * */
    //自定义handler类
    class MyHandler extends Handler{
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg)
        {
            Bundle bundle=msg.getData();

            Log.i("ClothesMainActivity:","arg:"+Integer.toString(msg.arg1));
            Context context = getApplicationContext();
            CharSequence text="";

            if(isDestroyed()||isFinishing())
                return;

            try {
                switch (msg.arg1)
                {
                    case 1:
                        Bundle bundle0=msg.getData();
                        String state = bundle0.get("mq.statue").toString();
                        if(state.compareTo("connect")==0)
                        {
                            ivmqtt.setImageResource(R.mipmap.mqtt_connect);

                            //toast = Toast.makeText(context, text, duration);
                            // .setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
                            // toast.show();
                        }
                        if(state.compareTo("disconnect")==0)
                        {
                            ivmqtt.setImageResource(R.mipmap.mqtt_disconnect);

                            //toast = Toast.makeText(context, text, duration);
                            // toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
                            //  toast.show();
                        }
                        break;
                    case 2:
                        break;
                    case 88:
                        {
                        Bundle bundle88 = msg.getData();
                        RfidData tmp = bundle88.getParcelable("rfiddata");


                        Log.i(TAG, tmp.type);
                        if (tmp.type.compareTo("02") == 0)
                            text = tmp.id;

                        if (tmp.type.compareTo("01") == 0) //worker order
                        {

                            try
                            {
                                String worker = tmp.data.substring(0, 6);
                                if (worker.compareTo("worker") == 0) {
                                    //logon task

                                    int d = tmp.data.toString().indexOf('*');


                                    if (d > tmp.data.length())
                                        return;
                                    Log.i(TAG, "len" + d);

                                    String wroknum = tmp.data.substring(6, d);
                                    // Toast.makeText(context, "工号:"+wroknum+"登陆", Toast.LENGTH_SHORT).show();
                                    MyToast.showToast(context, "工号:" + wroknum + "登陆");

                                    Config.fragShishishuju.sendRequestLogon(wroknum);

                                    return;
                                }

/*                            if(Config.fragmenthoudao==null&&Config.fragmenthoudaoqc==null)
                            {
                                MyToast.showToast(context,"刷订单卡，请切换到后道界面!");
                                return;
                            }

                            if(menu_index!=3&&menu_index!=4)
                            {
                                MyToast.showToast(context,"刷订单卡，请切换到后道界面!");
                                return;
                            }*/
                                text = tmp.data;
                                int a = text.toString().indexOf('(');
                                int b = text.toString().indexOf(')');
                                int c = text.toString().indexOf('#');
                                int d = text.toString().indexOf('*');

                                if (d > text.length())
                                    return;
                                Log.i(TAG, "len" + d);

                                if (a < 0 || b < 0 || c < 0 || d < 0 || a > b || b > c || c > d) {
                                    // 卡片数据格式错误
                                    Log.i(TAG, "订单卡卡片数据格式错误 a: " + Integer.toString(a) + " b: " + Integer.toString(b) + " c: " + Integer.toString(c) + " d "
                                            + Integer.toString(c));
    /*                            Toast toast0;
                                toast0 = Toast.makeText(context, "卡片数据格式错误", duration);
                                toast0.show();*/
                                    MyToast.showToast(context, "订单卡数据格式错误");

                                }
                                else
                                {
                                    Log.i(TAG, "a: " + Integer.toString(a) + " b: " + Integer.toString(b) + " c: " + Integer.toString(c) + " d "
                                            + Integer.toString(c));
                                    String ordeid = text.toString().substring(0, a);
                                    String styleid = text.toString().substring(a + 1, b);
                                    String num = text.toString().substring(b + 1, c);
                                    String line = text.toString().substring(c + 1, d);
                                    MyToast.showToast(context, "订单卡刷卡成功");
                                    Log.i(TAG, "menu_index: " + menu_index);
                                    Config.fragShishishuju.FlushRealData(ordeid, "",1,"");
/*                                if(Config.fragmenthoudao!=null&&menu_index ==3)
                                    Config.fragmenthoudao.dpsgetProcedureInfo(ordeid, styleid, num, line);

                                if(Config.fragmenthoudaoqc!=null&&menu_index ==4)
                                    Config.fragmenthoudaoqc.dpsgetProcedureInfo(ordeid, styleid, num, line);*/
                                }
                                //  Config.fragmenthoudao.dpsgetProcedureInfo("D180813-0001", "CZL15318-20-34", "10", "1");
                            }
                            catch (Exception e)
                            {
                                MyToast.showToast(context, "卡片数据格式错误，请重新发卡！");
                            }
                        }
                        break;
                    }
                    case 20:
                    {
                        Bundle bundle20 = msg.getData();
                        WorkerInfo tmp = bundle20.getParcelable("workerinfo");
                        tvName.setText(tmp.name);
                        tvLoginTime.setText(tmp.logontime);
                        break;
                    }
                    case 120:
                    {
                        tvName.setText("未登录");
                        tvLoginTime.setText("0000-00-00 00:00");
                    }
                    break;

                    case 801:
                    {
                        Bundle bundle801 = msg.getData();
                        WorkerInfo tmp = bundle801.getParcelable("dg.worker.info.update");
                        tvName.setText(tmp.name);
                        tvLoginTime.setText(tmp.logontime);
                    }
                    break;
                    case 100:
                    {
                        Bundle bundle100=msg.getData();
                        VerData tmp = bundle100.getParcelable("update");
                        String content ="有新版本发布: v"+tmp.ver;
                        String apkname = "tps10v"+tmp.ver+".apk";
                        APKNAME = apkname;
                        String url = "http://"+tmp.fileurl;
                        ShowDialog(0, "",content, url,apkname);

                        ISGETAPKVERSIONED = true;
                        if(settingDialog!=null)
                            settingDialog.dismiss();
                    }
                    break;

                    case 101: //Timer 获取版本号
                    {
                        Bundle bundle101=msg.getData();
                        String par = bundle101.get("par").toString();
                        Log.i(TAG,par);
                        if(par.compareTo("install")==0)
                        {
                            update();
                        }
                    }
                    break;
                    case 103:
                    {

                    }break;


                }
            }
            catch (Exception io)
            {
                io.printStackTrace();
                //MyToast.showToast(context,TAG+io.toString());
            }
        }
    }


    public class CalThread extends Thread
    {
        public Handler mHandler;
        public void run()
        {
            Looper.prepare();
            mHandler = new Handler()
            {
                // 定义处理消息的方法
                @Override
                public void handleMessage(Message msg)
                {
                    t1.calltype = fragment0.calltype;
                    t1.deal_reslut = fragment0.deal_result;
                    t1.call_flag = fragment0.call_flag;
                    Log.i("ClothesMainActivity:",Integer.toString(msg.arg1)+"   "+t1.calltype);
                }
            };
            Looper.loop();
        }
    }






    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)  {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            File file = new File(Environment.getExternalStorageDirectory() + "/Tps10");
                            if (!file.exists()) {
                                Log.d("result", "create result:" +file.toString()+":"+ file.mkdirs());
                                Config config = new Config(this);
                                config.init();
                                Config.Clothesath = file.toString();
                            }
                    }
                    break;
                }
        }
    }

    static {
        System.loadLibrary("native-lib");
    }
}
